package com.yonyou.cloud.member.adapters.repository.orm.dao.impl;

import com.yonyou.cloud.member.adapters.repository.orm.dao.MemberDao;
import com.yonyou.cloud.member.domainmodel.entities.member.Member;
import com.yonyou.cloud.member.domainmodel.vo.MemberId;
import com.yonyou.cloud.member.libs.key.KeyGenerator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MockMemberDaoImpl implements MemberDao, InitializingBean {
    @Autowired
    KeyGenerator keyGenerator;

    List<Member> members;

    @Override
    public void afterPropertiesSet() throws Exception {
        members = new ArrayList<>();
        members.add(new Member(keyGenerator.generate(MemberId.class), "张三", "18910721990").setLevel("白金"));
        members.add(new Member(keyGenerator.generate(MemberId.class), "李四", "13910721991").setLevel("青铜"));
        members.add(new Member(keyGenerator.generate(MemberId.class), "王五", "15910721992").setLevel("黄金"));
    }

    @Override
    public MemberId first() {
        return members.get(0).getId();
    }

    @Override
    public Member findById(MemberId id) {
        return members.stream().filter(m -> m.getId().equals(id)).findAny().orElse(null);
    }

    @Override
    public Member findByPhone(String phone) {
        return members.stream().filter(m -> m.getPhone().equals(phone)).findAny().orElse(null);
    }

    @Override
    public List<Member> listByLevel(String level) {
        return members.stream().filter(m -> level.equals(m.getLevel())).collect(Collectors.toList());
    }

    @Override
    public int count() {
        return members.size();
    }

    @Override
    public boolean insert(Member member) {
        return members.add(member);
    }

    @Override
    public boolean delete(MemberId id) {
        Iterator<Member> it = members.iterator();
        while (it.hasNext()) {
            if (it.next().getId().equals(id)) {
                it.remove();
                return true;
            }
        }
        return false;
    }
}